var moment       = require('moment');
var schedule     = require("node-schedule"); 
var request      = require('request');
var db           = require('../config/mongo_database');
var logger       = require('../config/log4js').logger('access');


// 30秒获取最新数据
schedule.scheduleJob('30 * * * * *', function(){  
	request.get('https://api.coinmarketcap.com/v1/ticker/?convert=CNY&limit=2000', function(err,httpResponse,body){
		if(err){
			logger.error('每分钟查询行情请求失败')
		}
		var object = JSON.parse(body);

		for(var i in object){
			saveOrUpdate(object[i])
		}
	})
}); 

// 30秒获取玩客币数据
schedule.scheduleJob('30 * * * * *', function(){  
	request.get('http://www.dyls.net/', function(err,httpResponse,body){
		if(err){
			logger.error('每分钟查询行情请求失败')
		}
		table(body)
	})

}); 

//  每天下午3点
schedule.scheduleJob('0 0 15 * * 0-7', function(){  
	request.get('https://api.coinmarketcap.com/v1/ticker/?convert=CNY&limit=2000', function(err,httpResponse,body){
		if(err){
			logger.error('每天查询行情请求失败')
		}
		var object = JSON.parse(body);

		for(var i in object){
			save(object[i])
		}
	})

}); 

function save(object){
	db.blistModel.findOne({"id":object['id']}, function(err, bcoin){
		if(bcoin==null){
			var blist = new db.blistModel();
			blist.key                = moment(new Date()).format("YYYYMMDD")
			blist.id                 = object['id']
			blist.name               = object['name']
			blist.symbol             = object['symbol']
			blist.rank               = object['rank']
			blist.price_usd          = object['price_usd']
			blist.price_btc          = object['price_btc']
			blist.esh_volume_usd     = object['24h_volume_usd']
			blist.market_cap_usd     = object['market_cap_usd']
			blist.available_supply   = object['available_supply']
			blist.total_supply       = object['total_supply']
			blist.max_supply         = object['max_supply']
			blist.percent_change_1h  = object['percent_change_1h']
			blist.percent_change_24h = object['percent_change_24h']
			blist.percent_change_7d  = object['percent_change_7d']
			blist.last_updated       = object['last_updated']
			blist.price_cny          = object['price_cny']
			blist.esh_volume_cny     = object['24h_volume_cny']
			blist.market_cap_cny     = object['market_cap_cny']
			blist.created            = new Date()

			blist.save(function(err){})
		}

	})
}

function saveOrUpdate(object){
	db.blistModel.findOne({"id":object['id']}, function(err, bcoin){
		if(bcoin==null){
			var blist = new db.blistModel();

			blist.id                 = object['id']
			blist.name               = object['name']
			blist.symbol             = object['symbol']
			blist.rank               = object['rank']
			blist.price_usd          = object['price_usd']
			blist.price_btc          = object['price_btc']
			blist.esh_volume_usd     = object['24h_volume_usd']
			blist.market_cap_usd     = object['market_cap_usd']
			blist.available_supply   = object['available_supply']
			blist.total_supply       = object['total_supply']
			blist.max_supply         = object['max_supply']
			blist.percent_change_1h  = object['percent_change_1h']
			blist.percent_change_24h = object['percent_change_24h']
			blist.percent_change_7d  = object['percent_change_7d']
			blist.last_updated       = object['last_updated']
			blist.price_cny          = object['price_cny']
			blist.esh_volume_cny     = object['24h_volume_cny']
			blist.market_cap_cny     = object['market_cap_cny']
			blist.created            = new Date()

			blist.save(function(err){})
		}else{
			if(object.id=='kyber-network'){
				object.rank = 4
			}
			if(object.id=='bitcoin-cash'){
				object.rank = 7
			}
			

			db.blistModel.update({"id":object['id']}, {"$set":object}, function(err){
			})
		}

	})
}


function table(message){
	String.prototype.replaceAll = function(s1,s2){
　　		return this.replace(new RegExp(s1,"gm"),s2);
　　}
	//过滤\n 转换成空
    var withoutRString = message.replaceAll(/(\r\n)|(\n)|(\t)|(\\)/g,'');
    var result_regex = new RegExp("<body.*>.*</body>");
    var result = withoutRString.match(result_regex)
    // 过滤nbsp标签
    var result2 = result[0].replaceAll('&nbsp;', '');

    //获取body中的所有table
	var regex = new RegExp("<table.*?>[\s\S]*?<\/table>");
	var html = result2.match(regex)

	var htmlc = html[0].replace('<table', '<table class="table"')
	
	htmlc = htmlc.replaceAll('<thead>', '<tbody>')
	htmlc = htmlc.replaceAll('</thead>', '</tbody>')
	htmlc = htmlc.replaceAll('<th>', '<td>')
	htmlc = htmlc.replaceAll('</th>', '</td>')
	htmlc = htmlc.replaceAll('<tr>', '<tr class="info1">')

	// 获取玩家网数据
	request.post({url:'http://www.chinawkb.com/ajax/allcoin_a/', form: {id:'u', t:0.28293053963068293}}, function(err,httpResponse,body){
		console.log(body)
		var data = JSON.parse(body)
		data = data['url']['wkb_cny']

		var wjhtml = '';

		if(data[7] > 0){
			wjhtml = '<tr class="info1"><td>玩家网</td><td><font color="red">'
				+ data[1]
				+ '↑</font></td><td>'
				+ data[2] + ' / ' + data[3]
				+ '</td><td>'
				+ data[4].toFixed(0)
				+ '</td>  <td><font color="red">'
				+ data[7]
				+ '%</font></td></tr>'
		}else{
			wjhtml = '<tr class="info1"><td>玩家网</td><td><font color="green">'
				+ data[1]
				+ '↓</font></td><td>'
				+ data[2] + ' / ' + data[3]
				+ '</td><td>'
				+ data[4].toFixed(0)
				+ '</td>  <td><font color="green">'
				+ data[7]
				+ '%</font></td></tr>'
		}	

		htmlc = htmlc.replace('</tbody>  <tbody>', '</tbody>  <tbody>' + wjhtml)

		db.bcoinModel.findOne({"btype": 'WKB'}, function(err, data){
			if(data==null){
				var bcoin = new db.bcoinModel();
				bcoin.name = '玩客币'
				bcoin.btype = 'WKB'
				bcoin.html = htmlc
				bcoin.save(function(err){
					console.log(err)
				})
			}else{
				db.bcoinModel.update({'btype': 'WKB'}, {"$set":{html:htmlc}}, function(err){
				})
			}
		})

	});
	

	
	
}

